// Package dao
// @Author zhongxc
// @Date 2024/1/17 10:42:00
// @Desc
package dao

import (
	"context"
	"math"
	commonModel "zhongxc.cc/admin-common/model"
	"zhongxc.cc/admin-common/msdb"
	"zhongxc.cc/admin-common/msdb/gorms"
	"zhongxc.cc/admin-user/internal/model"
)

type MenuDao struct {
	conn *gorms.GormConn
}

func NewMenuDao(db *msdb.MsDB) *MenuDao {
	return &MenuDao{
		conn: gorms.New(db.Conn),
	}
}

func (d *MenuDao) List(ctx context.Context, page int, rows int, keyword string) (*commonModel.PageResult, error) {
	session := d.conn.Session(ctx)

	// 总记录数
	var total int64
	var menuList []*model.SysMenu

	db := session.Model(&model.SysMenu{}).Debug()
	{
		if keyword != "" {
			db = db.Where("name like ?", "%"+keyword+"%")
		}
		db.Count(&total)
	}

	// 总分页数
	pageCount := math.Ceil(float64(total) / float64(rows))

	// 偏移量
	offset := (page - 1) * rows

	db = session.Model(&model.SysMenu{}).Debug()
	{
		if keyword != "" {
			db = db.Where("name like ?", "%"+keyword+"%")
		}
		err := db.Limit(rows).Offset(offset).Find(&menuList).Error
		if err != nil {
			return nil, err
		}
	}

	return commonModel.NewPageResult(menuList, page, pageCount, total, rows), nil
}
